package com.baitiaojun.common.utils.convert;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * 字符编码转换工具类
 */
@Slf4j
public class CharsetConvertUtils {

    public static final String ISO_8859_1 = "ISO-8859-1";

    public static final String UTF_8 = "UTF-8";

    public static final String GBK = "GBK";

    /**
     * 字符串类型字符编码转为Charset对象类型
     * @param originCharset
     * @return
     */
    public static Charset convert(String originCharset) {
        return StringUtils.isEmpty(originCharset) ? Charset.defaultCharset() : Charset.forName(originCharset);
    }


    /**
     * 字符编码转换, 默认自动转为utf-8
     * @param origin
     * @param originCharset
     * @param targetCharset
     * @return
     */
    public static String convert(String origin, String originCharset, String targetCharset) {
        //原字符编码默认为iso8859-1
        if (originCharset == null) {
            originCharset = CharsetConvertUtils.ISO_8859_1;
        }
        //默认自动转为utf-8
        if (targetCharset == null) {
            targetCharset = CharsetConvertUtils.UTF_8;
        }
        //如果字符串为空或者源字符集是目标字符集, 就返回原字符串
        if (origin == null || originCharset.equals(targetCharset)) {
            return origin;
        }
        String newStr = null;
        try {
            newStr = new String(origin.getBytes(originCharset), targetCharset);
        } catch (UnsupportedEncodingException e) {
            log.warn("字符编码转换失败:{}", e.getMessage());
        }
        return newStr;
    }

    /**
     * 获取系统默认字符编码
     * @return
     */
    public static String defaultSysCharset() {
        return Charset.defaultCharset().name();
    }
}
